给定一个单链表的头结点pHead(该头节点是有值的,比如在下图,它的val是1),长度为n,反转该链表后,返回新链表的表头。
数据范围:
要求:空间复杂度 ,时间复杂度 。
如当输入链表{1,2,3}时,
经反转后,原链表变为{3,2,1},所以对应的输出为{3,2,1}。
以上转换过程如下图所示:
{1,2,3}
{3,2,1}
{}
{}
空链表则输出空
class Solution: def ReverseList(self , head: ListNode) -> ListNode: # write code here tail = head if(tail != None): while(tail.next != None):#寻找尾结点 tail = tail.next while(head != tail ): point2 = head head = head.next point2.next = tail.next tail.next = point2 return tail三个指针分别指向头结点(head)、尾结点(tail)和待移动节点(point2)。
# class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param head ListNode类 # @return ListNode类 # class Solution: def ReverseList(self , head: ListNode) -> ListNode: ## 直接反转 cur = head pre = None while (cur != None): temp = cur.next ## 保存cur.next之后的内容 cur.next = pre ## 完成反转指向 pre = cur ## 交换 pre和cur cur = temp return pre class Solution: def ReverseList(self , head: ListNode) -> ListNode: ## 链表 ———> 数组 ————> 反转数组 ————> 链表 ### 由链表生成数组 dummy = ListNode(-1) dummy.next = head cur = dummy alist = [] while (cur.next != None): cur = cur.next alist.append(cur.val) alist.reverse() ## 翻转 ## 由数组生成链表 dummy = ListNode(-1) dummy.next = head cur = dummy for i in range(len(alist)): cur.next = ListNode(alist[i]) cur = cur.next return dummy.next
class Solution: def ReverseList(self , head: ListNode) -> ListNode: # write code here if head==None: return None elif head.next==None: return head else: head_next=head.next head_next_two=head.next.next head.next=None #容易忽略了的 while head_next_two: head_next.next=head head=head_next head_next=head_next_two head_next_two=head_next_two.next head_next.next=head return head_next
# class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param head ListNode类 # @return ListNode类 # class Solution: def ReverseList(self , head: ListNode) -> ListNode: # write code here #迭代 if head == None: return head rev = None while head: tmp = head.next head.next = rev rev = head head = tmp return rev #递归 # import sys # sys.setrecursionlimit(1000000) #递归最多1000次左右,改变递归最大深度 # if head == None&nbs***bsp;head.next == None: # return head # rev = self.ReverseList(head.next) # head.next.next = head # head.next = None # return rev
class Solution: def ReverseList(self , head: ListNode) -> ListNode: rev_head = None while head is not None: curr = head head = head.next curr.next = rev_head rev_head = curr return rev_head
# class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param head ListNode类 # @return ListNode类 # class Solution: def ReverseList(self , head: ListNode) -> ListNode: if head == None: return None temp0 = None temp1 = head temp2 = head.next temp1.next = temp0 while temp2 != None : temp0 = temp1 temp1 = temp2 temp2 = temp2.next temp1.next = temp0 return temp1